/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.service.data.entitydiff.value;

import io.swagger.v3.oas.annotations.media.Schema;
import org.apache.commons.beanutils.BeanUtils;
import yhao.infra.service.data.entitydiff.DiffActor;
import yhao.infra.service.data.entitydiff.DiffResult;

import java.lang.reflect.Field;
import java.util.Map;


/**
 * data-entityDiff数据对比工具带value映射的默认实现
 *
 * @see DiffActor
 * @author yoara
 */
public class DefaultDiffValueActor implements DiffActor<DiffValueParam>{
    @Override
    public void doAct(DiffValueParam param, DiffResult result) {
        StringBuilder content = new StringBuilder();
        try{
            for(Map.Entry<String,DiffValueOperator> entry:param.getFieldMap().entrySet()){
                Field field = param.getEntity().getClass().getDeclaredField(entry.getKey());
                String oldValue = BeanUtils.getProperty(param.getHistoryEntity(),entry.getKey());
                String newValue = BeanUtils.getProperty(param.getEntity(),entry.getKey());
                Schema ap = field.getAnnotation(Schema.class);
                String desc = ap==null?field.getName():ap.name();
                if((newValue==null&&oldValue!=null) || !newValue.equals(oldValue)){
                    oldValue = entry.getValue().doOperator(oldValue);
                    newValue = entry.getValue().doOperator(newValue);
                    content.append("[").append(desc).append("]:\"").append(oldValue)
                            .append("\"->\"").append(newValue).append("\".");
                }
            }
        }catch (Exception e){
            result.setErrMessage(e.getMessage());
        }
        result.setResult(true);
        result.setData(content.toString());
    }
}
